package utils

import (
	"crypto/rand"
	"encoding/base64"

	"github.com/matthewhartstonge/argon2"
)

// 生成随机盐值
func GenerateSalt() (string, error) {
	salt := make([]byte, 16)
	_, err := rand.Read(salt)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(salt), nil
}

// 使用Argon2计算密码哈希
func HashPassword(password string, salt string) (string, error) {
	// 解码base64格式的盐值
	saltBytes, err := base64.StdEncoding.DecodeString(salt)
	if err != nil {
		return "", err
	}

	// 配置Argon2参数
	argon := argon2.DefaultConfig()

	// 将密码和盐值合并
	combined := append([]byte(password), saltBytes...)

	// 计算哈希
	hash, err := argon.HashEncoded(combined)
	if err != nil {
		return "", err
	}

	return string(hash), nil
}

// 验证密码
func VerifyPassword(password, encodedHash string) (bool, error) {
	ok, err := argon2.VerifyEncoded([]byte(password), []byte(encodedHash))
	if err != nil {
		return false, err
	}
	return ok, nil
}
